<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NLWeb Dropdown Chat - Integration Example</title>
    
    <!-- Include the dropdown chat CSS -->
    <link rel="stylesheet" href="common-chat-styles.css">
    <link rel="stylesheet" href="nlweb-dropdown-chat.css">

    <!-- Include DOMPurify for HTML sanitization -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js" integrity="sha512-H+rglffZ6f5gF7UJgvH4Naa+fGCgjrHKMgoFOGmcPTRwR6oILo5R+gtzNrpDp7iMV3udbymBVjkeZGNz1Em4rQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <!-- Page-specific styles -->
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .header {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .header h1 {
            margin: 0 0 10px 0;
            color: #2c3e50;
        }
        
        .header p {
            margin: 0;
            color: #666;
        }
        
        
        .section {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .section h2 {
            margin-top: 0;
            color: #2c3e50;
        }
        
        /* Custom styling for the search container */
        #recipe-search-container {
            margin-bottom: 30px;
        }
        
        #product-search-container {
            max-width: 500px;
            margin: 20px 0;
        }
        
        pre {
            background: #f4f4f4;
            padding: 15px;
            border-radius: 4px;
            overflow-x: auto;
        }
        
        code {
            background: #f4f4f4;
            padding: 2px 4px;
            border-radius: 2px;
            font-family: 'Courier New', monospace;
        }
        
        .code-section {
            margin-top: 20px;
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 8px 0;
            padding-left: 25px;
            position: relative;
        }
        
        .feature-list li:before {
            content: "✓";
            position: absolute;
            left: 0;
            color: #27ae60;
            font-weight: bold;
        }
        
        /* Status message styles */
        .status {
            padding: 10px 15px;
            border-radius: 4px;
            margin: 10px 0;
            font-size: 14px;
        }
        
        .status.error {
            background: #fee;
            color: #c00;
            border: 1px solid #fcc;
        }
        
        .status.success {
            background: #efe;
            color: #060;
            border: 1px solid #cfc;
        }
        
        .status.info {
            background: #e7f3ff;
            color: #004085;
            border: 1px solid #b8daff;
        }
        
        .status.warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeeba;
        }
        
        #console-output {
            background: #1e1e1e;
            color: #d4d4d4;
            padding: 15px;
            border-radius: 4px;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 12px;
            max-height: 400px;
            overflow-y: auto;
            margin-top: 10px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        
        #console-output .log-entry {
            margin: 2px 0;
            line-height: 1.4;
        }
        
        #console-output .log-error {
            color: #f48771;
        }
        
        #console-output .log-warn {
            color: #dcdcaa;
        }
        
        #console-output .log-info {
            color: #4ec9b0;
        }
        
        #console-output .log-success {
            color: #4fc1ff;
        }
        
        .debug-section {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }
        
        .debug-section h3 {
            margin-top: 0;
            color: #495057;
            font-size: 16px;
        }
        
        .debug-controls {
            margin: 10px 0;
        }
        
        .debug-controls button {
            margin-right: 10px;
            padding: 6px 12px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .debug-controls button:hover {
            background: #0056b3;
        }
        
        .debug-controls button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>NLWeb Dropdown Chat Example</h1>
        <p>This page demonstrates the NLWeb Dropdown Chat component for recipe search with debugging</p>
    </div>
    
    <div class="section" style="max-width: 800px; margin: 0 auto;">
        <h2>Recipe Search</h2>
        <p>Try searching for recipes using natural language queries:</p>
        
        <!-- Status display -->
        <div id="status"></div>
        
        <!-- Search box instance -->
        <div id="recipe-search-container"></div>
        
        <div style="margin-top: 30px;">
            <h3>Example queries:</h3>
            <ul>
                <li>Chocolate cake recipes</li>
                <li>Spicy vegetarian dishes</li>
                <li>Quick pasta recipes under 30 minutes</li>
                <li>Remember that I'm vegetarian</li>
            </ul>
        </div>
        
        <!-- Debug section -->
        <div class="debug-section">
            <h3>Debug Information</h3>
            <div class="debug-controls">
                <button onclick="window.checkStatus()">Check Status</button>
                <button onclick="window.clearConsole()">Clear Console</button>
                <button onclick="window.testSearch()">Test Search</button>
            </div>
            <div id="console-output"></div>
        </div>
        
        <div class="code-section">
            <h3>Features:</h3>
            <ul class="feature-list">
                <li>Natural language search</li>
                <li>Conversation history </li>
                <li>Memory for user preferences</li>
                <li>Follow-up questions support</li>
                <li>Clean dropdown interface</li>
            </ul>
            
            <h3>Integration Code:</h3>
            <pre><code>&lt;!-- Include CSS --&gt;
&lt;link rel="stylesheet" href="nlweb-dropdown-chat.css"&gt;

&lt;!-- Add container --&gt;
&lt;div id="recipe-search-container"&gt;&lt;/div&gt;

&lt;!-- Include JavaScript --&gt;
&lt;script type="module"&gt;
  import { NLWebDropdownChat } from './nlweb-dropdown-chat.js';
  
  const chat = new NLWebDropdownChat({
    containerId: 'recipe-search-container',
    site: 'seriouseats',
    placeholder: 'Search for recipes...',
    endpoint: window.location.origin
  });
&lt;/script&gt;</code></pre>
        </div>
    </div>
    
    <!-- Include the dropdown chat JavaScript -->
    <script type="module">
        const statusEl = document.getElementById('status');
        const consoleOutput = document.getElementById('console-output');
        
        // Enhanced console logging
        const originalLog = console.log;
        const originalError = console.error;
        const originalWarn = console.warn;
        const originalInfo = console.info;
        
        function addToConsole(type, ...args) {
            const timestamp = new Date().toISOString().split('T')[1].split('.')[0];
            const msg = args.map(arg => {
                if (typeof arg === 'object') {
                    try {
                        return JSON.stringify(arg, null, 2);
                    } catch (e) {
                        return String(arg);
                    }
                }
                return String(arg);
            }).join(' ');
            
            const entry = document.createElement('div');
            entry.className = `log-entry log-${type.toLowerCase()}`;
            entry.textContent = `[${timestamp}] [${type}] ${msg}`;
            consoleOutput.appendChild(entry);
            consoleOutput.scrollTop = consoleOutput.scrollHeight;
        }
        
        // Override console methods
        console.log = (...args) => {
            originalLog(...args);
            addToConsole('LOG', ...args);
        };
        
        console.error = (...args) => {
            originalError(...args);
            addToConsole('ERROR', ...args);
        };
        
        console.warn = (...args) => {
            originalWarn(...args);
            addToConsole('WARN', ...args);
        };
        
        console.info = (...args) => {
            originalInfo(...args);
            addToConsole('INFO', ...args);
        };
        
        // Helper functions
        function setStatus(message, type = 'info') {
            statusEl.innerHTML = `<div class="status ${type}">${message}</div>`;
        }
        
        window.clearConsole = function() {
            consoleOutput.innerHTML = '';
            addToConsole('INFO', 'Console cleared');
        };
        
        window.checkStatus = function() {
            if (window.nlwebChat) {
                addToConsole('INFO', 'Chat instance found:', {
                    container: !!window.nlwebChat.container,
                    searchInput: !!window.nlwebChat.searchInput,
                    dropdownResults: !!window.nlwebChat.dropdownResults,
                    chatInterface: !!window.nlwebChat.chatInterface,
                    conversationManager: window.nlwebChat.chatInterface ? !!window.nlwebChat.chatInterface.conversationManager : false,
                    currentConversationId: window.nlwebChat.chatInterface ? window.nlwebChat.chatInterface.currentConversationId : null,
                    selectedSite: window.nlwebChat.chatInterface ? window.nlwebChat.chatInterface.selectedSite : null
                });
                setStatus('✓ Chat instance is active', 'success');
            } else {
                addToConsole('ERROR', 'Chat instance not found');
                setStatus('✗ Chat instance not found', 'error');
            }
        };
        
        window.testSearch = function() {
            if (window.nlwebChat && window.nlwebChat.searchInput) {
                const testQuery = 'chocolate cake recipe';
                addToConsole('INFO', `Testing search with query: "${testQuery}"`);
                window.nlwebChat.searchInput.value = testQuery;
                window.nlwebChat.handleSearch();
                setStatus('Test search initiated', 'info');
            } else {
                addToConsole('ERROR', 'Cannot test search - chat not initialized');
                setStatus('Cannot test search - chat not initialized', 'error');
            }
        };
        
        // Initialize the dropdown chat
        async function initializeDropdownChat() {
            try {
                setStatus('Loading NLWebDropdownChat module...', 'info');

                // Check if container exists before import
                const container = document.getElementById('recipe-search-container');
                if (!container) {
                    throw new Error('Container element not found');
                }
                
                const { NLWebDropdownChat } = await import('./nlweb-dropdown-chat.js');
                
                setStatus('Creating chat instance...', 'info');
                
                // Initialize the search instance
                const chat = new NLWebDropdownChat({
                    containerId: 'recipe-search-container',
                    site: 'seriouseats',
                    placeholder: 'Search for recipes...',
                    endpoint: window.location.origin,
                    inputId: 'recipe-chat-input'  // Optional: specify a custom input ID
                });
                
                // Make it available for debugging
                window.nlwebChat = chat;
                
                // Monitor initialization progress
                let checkCount = 0;
                const checkInterval = setInterval(() => {
                    checkCount++;

                    if (chat.chatInterface) {
                        clearInterval(checkInterval);
                        setStatus('✓ Dropdown chat initialized successfully!', 'success');
                    } else if (checkCount >= 20) { // Stop after 10 seconds
                        clearInterval(checkInterval);
                        setStatus('✗ Chat interface failed to initialize after 10 seconds', 'error');
                    }
                }, 500);
                
            } catch (error) {
                setStatus(`✗ Failed to initialize: ${error.message}`, 'error');
            }
        }
        
        // Start initialization when page loads
        initializeDropdownChat();
    </script>
</body>
</html>